import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
import { Logger } from '@/common/log4js/log4j.util';
import { InjectRepository } from '@nestjs/typeorm';
import { Log } from '@/modules/system/log/entities/log.entity';
import { Repository } from 'typeorm';
import { argumentsToString } from '@/common/utils/common.util';

// 拦截全部类型
@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
    constructor(
        @InjectRepository(Log)
        private readonly logRepository: Repository<Log>,
    ) {
    }

    catch(exception: any, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse();
        const request = ctx.getRequest();
        const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
        const logFormat = `-----------------------------------------------------------------------
      Request original url: ${request.originalUrl}
      Method: ${request.method}
      IP: ${request.ip}
      Status code: ${status}
      Response: ${exception}
      -----------------------------------------------------------------------
      `;
        if (status !== 404) {
            Logger.error(logFormat);
            this.logRepository.save({
                ip: request.ip,
                userFlag: request?.user?.username || request.headers?.code,
                name: '服务器错误',
                method: request.method,
                message: exception.message,
                arguments: argumentsToString(request), // (request.body || request.params || request.query),
                status,
                path: request.originalUrl,
                type: 0,
            });
        }
        console.log("-------------------------------------")
        console.log('走了global-exception.filter.ts');
        console.log("-------------------------------------")
        response.status(status).send({
            code: status,
            msg: `Service Error: ${exception}`,
            // error: `${exception}`,
        });
    }
}
